using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Admin_AddNewUser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblRoles.Visible = false;

        if(!Page.IsPostBack)
        {
            foreach(string role in Roles.GetAllRoles())
            {
                cblRoles.Items.Add(role);
            }
        }
    }

    protected void btnAddUser_Click(object sender, EventArgs e)
    {
        MembershipCreateStatus createStatus;
        MembershipUser newUser = Membership.CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtSecureQ.Text,
            txtSecureA.Text, true, out createStatus);

        if(newUser == null)
        {
            //failed to create new account - display message from MembershipUser object
            lblFailure.Text = GetErrorMessage(createStatus);
        }
        else
        {
            //user created - add user to selected role(s) and redirect to default
            for(int i = 0; i < cblRoles.Items.Count; i++)
            {
                if(cblRoles.Items[i].Selected == true)
                    Roles.AddUserToRole(txtUsername.Text, cblRoles.Items[i].Text);
            }
            Response.Redirect("ManageUsers.aspx");

        }
    }


    public string GetErrorMessage(MembershipCreateStatus status)
    {
        switch(status)
        {
            case MembershipCreateStatus.DuplicateUserName:
            return "Username already exists. Please enter a different user name.";

            case MembershipCreateStatus.DuplicateEmail:
            return "A username for that e-mail address already exists. Please enter a different e-mail address.";

            case MembershipCreateStatus.InvalidPassword:
            return "The password provided is invalid. Please enter a valid password value.";

            case MembershipCreateStatus.InvalidEmail:
            return "The e-mail address provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidAnswer:
            return "The password retrieval answer provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidQuestion:
            return "The password retrieval question provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidUserName:
            return "The user name provided is invalid. Please check the value and try again.";

            default:
            return "An error has occurred. Please verify your entry and try again.";
        }
    }
}
